package cc.chinagps.gateway.mq.writer;

import cc.chinagps.gateway.buff.GBossDataBuff;
import cc.chinagps.gateway.common.Config;

import javax.jms.BytesMessage;
import javax.jms.Session;
import java.util.List;

public class EGPacketWriter extends AbstractWriter<GBossDataBuff.EGPacketInfo> {

    public EGPacketWriter(Session session) {
        super(session, Config.MQ.EG_PACKET_NAME, Config.MQ.EG_PACKET_TYPE, Config.MQ.EG_PACKET_MODE, Config.MQ.EG_PACKET_CACHE_SIZE);
    }

    @Override
    protected void saveDataToMQ(List<GBossDataBuff.EGPacketInfo> list) throws Exception {
        int compressCount = 0;
        GBossDataBuff.EGPacketInfoList.Builder builder = GBossDataBuff.EGPacketInfoList.newBuilder();
        for (int i = 0; i < list.size(); i++) {
            builder.addPackets(list.get(i));
            compressCount++;
            if (compressCount >= Config.MQ.COMPRESS_SIZE) {
                BytesMessage msg = session.createBytesMessage();
                msg.writeBytes(builder.build().toByteArray());
                producer.send(msg);
                session.commit();
                compressCount = 0;
                if (i != (list.size() - 1)) {
                    builder = GBossDataBuff.EGPacketInfoList.newBuilder();
                }
            }
        }

        if (compressCount > 0) {
            BytesMessage msg = session.createBytesMessage();
            msg.writeBytes(builder.build().toByteArray());
            producer.send(msg);
            session.commit();
        }
    }
}
